<template>
  <div>
    <TopFilter ref="topFilter" :list="topFilterList" :cols="4" :collapse="false" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      columnsRef="partPartOtherPartObliIndex"
      :dataSource="dataSource"
      :onSyncTableData="getAll"
      :onCellChange="changeQuantity"
      :rowstyles="styleList"
      :isMemoryPagination="true"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="columns => (this.selectColumns = columns)"
    >
      <template slot="controls">
        <el-button size="small" type="primary" :disabled="btn0" icon="el-icon-plus" @click="toAddBtn">新建</el-button>
        <!-- <el-button size="small" type="primary" icon="el-icon-plus" :disabled="btn" @click="addHandle">新增</el-button> -->
        <!-- <el-button size="small" type="primary" :disabled="btn1" @click="hold()">预留</el-button>
        <el-button size="small" type="primary" :disabled="btn2" @click="close()">解预留</el-button>
        <el-button size="small" @click="reset">取消</el-button> -->
      </template>
    </FilterTable>
    <!-- <div style="text-align:center">

    </div> -->
    <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <BrandModal :ptype="ptype" :type="handleType" :rowData="formData" :obligatedNo="this.obligatedNo" @close="closeHandler" @getData="getData" />
    </BaseDialog>
    <Drawer :visible.sync="visible1" :title="dialogTitle1" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <add :type="handleType1" :rowData="formData1" @close="closeHandler1" @getAddData="getAddData" />
    </Drawer>
    <BaseDialog title="预留单新增" :visible.sync="visible2" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <new-obligated :type="handleType1" @close="closeHandler2" @refuse="refuse" />
    </BaseDialog>
    <BaseDialog title="预留单详情" :visible.sync="visible3" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <obligated-items :obligatedNo="this.obligatedNo" @close="closeHandler3" />
    </BaseDialog>
    <BaseDialog title="预留单编辑" :visible.sync="visible4" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <eidt-obligated-items :obligatedNo="this.obligatedNo" @close="closeHandler4" @refuse="refuse" :type="handleType" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { queryPartObligatedItem, performExecute, performExecutes, querys } from '@/api/part/partOther/partObli';
import BrandModal from './tabs/brandModal';
import { searchStroageList } from '@/api/part/partOther/partWaterBook';
import add from './tabs/add';
import { queryAllPartObligatedList } from '@/api/part/partOther/partObliQuery';
import moment from 'moment';
import { log } from 'util';
import { getUserId } from '@/assets/js/auth';
import { getAllUser } from '@/api/customerRepair/afterSaleVisit/resultEntry';
import { arrayObjDeWeight, confirmAction, jsonToHump } from '@/utils';
import NewObligated from './newObligated.vue';
import ObligatedItems from './obligatedItems.vue';
import EidtObligatedItems from './eidtObligatedItems';
// import { confirmAction, notifyAction } from '@/utils';
export default {
  name: 'Brand',
  components: {
    BrandModal,
    add,
    NewObligated,
    ObligatedItems,
    EidtObligatedItems
  },
  mixins: [dictionary],
  data() {
    this.conf = { add: '确定', edit: '编辑', show: '显示' };
    this.BaseTable = null;
    this.tableData = [];
    return {
      chooseFlag: 0,
      selectColumns: [],
      topFilterList: this.createTopFilterList(),
      fetchParams: {},
      dataSource: [],
      visible: false,
      formDatagongdan: '',
      visible1: false,
      visible2: false,
      visible3: false,
      handleTypegongdan: '',
      dialogTitle: '',
      dialogTitle1: '',
      columns: this.createTableColumns(),
      handleType: '',
      handleType1: '',
      formData: {},
      formData1: {},
      arr: {},
      visiblegongdan: false,
      dialogTitlegongdan: '',
      styleList: [],
      yuliudan: false,
      btn: true,
      btn0: false,
      btn1: true,
      btn2: true,
      btnDisabled: false,
      itemIds: '',
      eidtDisabled: false,
      codeName: [],
      userId: '',
      visible4: false,
      obligatedNo: null,
      partFlag: false, // 预约数量
      setPerformExecuteFlag: false
    };
  },
  computed: {
    ptype() {
      return this.$route.meta.ptype;
    } // 模块区分
  },
  watch: {
    setPerformExecuteFlag() {
      this.getAll();
    }
  },
  mounted() {
    this.initSelect();
    this.getCode();
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.flag3 = true;
  },

  methods: {
    // 删除操作
    async removeRecordHandle() {
      await confirmAction('此操作将删除该记录, 是否继续?');
      this.$refs.table.EXECUTE_DELETE(this.selectColumns);
    },
    async initSelect() {
      let res = await getAllUser();
      // 去重
      let dataList = arrayObjDeWeight(res.data, 'userId');
      this.columns.find(item => item.dataIndex === 'applicant').dictItems = dataList.map(x => ({ text: x.employeeName, value: x.userId }));
      this.columns.find(item => item.dataIndex === 'applicant').filterItems = dataList.map(x => ({ text: x.employeeName, value: x.userId }));
    },
    getAddData(x, y) {
      // this.visible1 = false;  添加页面的弹窗false关闭
      const flag = this.dataSource.find(item => {
        const isHave = item['partNo'] === y['partNo'];
        const isRuZhang = item['storageCode'] == y['storageCode'];
        return isHave && isRuZhang;
      });
      console.log(flag);
      if (flag) {
        this.$notify({
          title: '警告',
          message: '配件已存在',
          type: 'warning'
        });
        return;
      }
      this.$notify.success({ title: '提示信息', message: '添加成功!' });
      this.btn0 = this.btn2 = true;
      this.btn1 = false;
      this.dataSource = [...this.dataSource, y];
      // this.BaseTable.EXECUTE_INSERT([y]);
      this.chooseFlag = 1;
    },
    createTopFilterList() {
      let that = this;
      return [
        {
          type: 'INPUT',
          label: '预留单号',
          fieldName: 'obligatedNo',
          disabled: false,
          placeholder: '请选择'
          // unitRender: () => {
          //   return (
          //     <div>
          //       <el-button slot="append" icon="el-icon-search" disabled={this.yuliudan} onClick={() => this.searchAll()}></el-button>
          //     </div>
          //   );
          // }
        },
        {
          type: 'INPUT',
          label: '预约单号',
          fieldName: 'sheetNo',
          placeholder: '请选择'
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          placeholder: '请选择'
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName',
          placeholder: '请选择'
        },
        {
          type: 'INPUT',
          label: '车主',
          fieldName: 'ownerName',
          placeholder: '请输入'
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          placeholder: '请输入'
        },
        // {
        //   type: 'SELECT',
        //   label: '仓库名称',
        //   fieldName: 'storageCode',
        //   placeholder: '请选择...',
        //   itemList: this.createDictList('1004'),
        //   initialValue: 10041001
        // },
        {
          type: 'RANGE_DATE',
          label: '预留日期',
          fieldName: 'obligatedBeginDate|obligatedEndDate',
          // placeholder: '请选择缺料日期',
          initialValue: [`${moment().get('year')}-${moment().get('month') + 1}-01`, moment().format('YYYY-MM-DD')],
          valueFormat: 'yyyy-MM-dd'
        },
        {
          type: 'SELECT',
          label: '预留状态',
          fieldName: 'isObligatedList',
          placeholder: '请选择...',
          itemList: this.createDictList('9994')
        }
      ];
    },
    async closeHandler4(type) {
      this.visible4 = false;
      let data = await this.$refs.topFilter.GET_FORM_DATA();
      this.changeHandle(data);
      let res1 = await queryAllPartObligatedList(this.fetchParams);
      this.dataSource = res1.data;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams1 = { ...this.fetchParams };
      }
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'indexaa',
          width: 90,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 120,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={props.row.isObligatedList == 99941003 || props.row.sheetNo ? true : false} onClick={() => this.editItems(props.row)}>
                  编辑
                </el-button>
                <el-button size="mini" type="text" onClick={() => this.showItems(props.row)}>
                  详情
                </el-button>
              </div>
            );
          }
        },
        {
          title: '预留单号',
          dataIndex: 'obligatedNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '预约单号',
          dataIndex: 'sheetNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '预留状态',
          dataIndex: 'isObligatedList',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('9994'),
          render: props => {
            return <span>{this.createDictText(props.row.isObligatedList, '9994')}</span>;
          }
        },
        {
          filterType: 'input',
          title: '车主',
          dataIndex: 'ownerName'
        },
        {
          filterType: 'input',
          title: '车牌号',
          dataIndex: 'license'
        },
        {
          title: '操作人',
          dataIndex: 'applicant',
          showOverflowTooltip: true,
          sorter: true,
          // filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dictItems: []
        },

        {
          title: '预留总数量',
          dataIndex: 'quantity',
          // disabled: false,
          precision: 2,
          editable: false,
          // min: 1,
          editType: 'number',
          editPattern: /^(?!0\d|[0.]+$)\d+(\.\d{2})?$/,
          sorter: true,
          filter: true,
          filterType: 'number',
          // onChange: (val, row) => {
          //   row.costAmount = eval(row.costPrice * row.quantity);
          // },
          // onInput: (val, row) => {
          //   row.costAmount = eval(row.costPrice * row.quantity);
          // },
          summation: true
        },

        {
          title: '预留日期',
          dataIndex: 'applyDate',
          filterType: 'date-range',
          width: 150,
          dateFormat: 'yyyy-MM-dd HH:mm:SS',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '预留天数',
          dataIndex: 'applyDay',
          filterType: 'input',
          width: 150,
          sorter: true,
          filter: true
        }
      ];
    },
    async getCode() {
      this.userId = await getUserId();
      let res = (await searchStroageList()).data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      this.codeName = res;
    },

    changeQuantity(val1, val2) {
      console.log(val1, 'val1');
      console.log(val2, 'val2');
      console.log(val1[Object.keys(val1)[0]], '修改后对应的编码');
      let value = val1[Object.keys(val1)[0]];
      if (value < 0.01) {
        this.partFlag = true;
      } else {
        this.partFlag = false;
      }
      if (val2.isObligated == 10041001) {
        this.btn1 = false;
      }
      if (Number(val2.useableStock) < Number(val2.quantity)) {
        return this.$notify.warning({ title: '提示信息', message: '预留数量不能大于可用库存！' });
      }
    },

    // changeQuantity(a, val) {
    //   if (val.isObligated == 10041001) {
    //     this.btn1 = false;
    //   }
    //   if (Number(val.useableStock) < Number(val.quantity)) {
    //     return this.$notify.warning({ title: '提示信息', message: '出库数量不能大于可用库存！' });
    //   }
    // },
    getStorageName(storageCode) {
      const item = this.codeName.find(x => {
        return x.value == storageCode;
      });
      return item ? item.text : '';
    },
    getAll(val, value) {
      // console.log(val, 'vallll-----');
      // console.log(value, 'valuelll-----');
      this.tableData = val;
      val.forEach(x => {
        if (x.applyDay != null && x.applyDay != undefined && x.applyDay != '') {
          if (Number(x.applyDay) > 7) {
            this.styleList.push({ row: x, styles: { backgroundColor: '#ffd200' } });
          } else {
            this.styleList = this.styleList.filter(y => y.row != x);
          }
        }
      });
      console.log(this.tableData);
      // if (this.setPerformExecuteFlag) {
      // }
    },
    async closeHandler3() {
      this.visible3 = false;
      let res1 = await queryAllPartObligatedList(this.fetchParams);
      this.dataSource = res1.data;
    },
    showItems(val) {
      this.obligatedNo = val.obligatedNo;
      this.visible3 = true;
      console.log('this.obligatedNo::', this.obligatedNo);
    },
    editItems(val) {
      this.obligatedNo = val.obligatedNo;
      this.visible4 = true;
    },
    // 预留
    hold() {
      if (!this.partFlag) {
        if (this.selectColumns.length <= 0) {
          this.$notify.warning({ title: '提示信息', message: '请选择要预留的配件！' });
          return;
        }
        this.$confirm('是否确定预留？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let obj = {
            obligatedNo: this.topFilterList.find(item => item.fieldName === 'obligatedNo').initialValue || '',
            applicant: this.topFilterList.find(item => item.fieldName === 'applicant').initialValue || '',
            owenNo: this.topFilterList.find(item => item.fieldName === 'ownerNo').initialValue || '',
            ownerName: this.topFilterList.find(item => item.fieldName === 'ownerName').initialValue || '',
            license: this.topFilterList.find(item => item.fieldName === 'license').initialValue || '',
            remark: this.topFilterList.find(item => item.fieldName === 'remark').initialValue || '',
            itemIds: this.itemIds || '',
            tables: this.selectColumns,
            // 模块区分
            ptype: this.ptype ? this.ptype : null
          };
          // console.log(obj, '----obj----');
          let a = (this.btnDisabled = true);
          this.columns.find(x => x.dataIndex === 'quantity').disabled = true;
          if (this.tableData.length == 0) {
            a = false;
            return this.$notify.warning({ title: '提示信息', message: '请添加需要预留的配件！' });
          }
          this.tableData.forEach(x => {
            // 增加预留数量判断
            if (x.quantity <= 0) {
              a = false;
              return this.$notify.warning({ title: '提示信息', message: '请输入预留数量！' });
            }
            if (Number(x.useableStock) < Number(x.quantity)) {
              a = false;
              return this.$notify.warning({ title: '提示信息', message: '预留数量不能大于可用库存！' });
            }
          });
          if (a) {
            this.getperformExecutes(obj);
          }
          // debugger;
        });
      }
    },

    async getperformExecutes(val) {
      const res = await performExecutes(val);
      this.obligatedNo = res.data.obligatedNo;
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '预留成功！' });
        this.topFilterList.find(item => item.fieldName === 'obligatedNo').initialValue = this.obligatedNo;

        let res = await queryPartObligatedItem({ obligatedNo: this.obligatedNo });
        this.dataSource = res.data;
        this.topFilterList.find(item => item.fieldName === 'applicant').disabled = true;
        this.btn = this.btn1 = true;
        this.btn2 = false;
      }
    },
    refuse() {
      this.$refs.table.RESET_FORM();
    },
    // 解预留
    close() {
      console.log(this.selectColumns, 'selectColumns');
      let ID = '';
      if (this.selectColumns.length <= 0) {
        this.$notify.warning({ title: '提示信息', message: '请选择要解预留的配件！' });
      } else {
        this.$confirm('是否确定解预留？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.selectColumns.forEach(x => {
            if (x.isObligated === 10041001) {
              ID = ID + ',' + x.itemId;
            }
          });
          let res = {
            obligatedNo: this.topFilterList.find(item => item.fieldName === 'obligatedNo').initialValue ? this.topFilterList.find(item => item.fieldName === 'obligatedNo').initialValue : '',
            applicant: this.topFilterList.find(item => item.fieldName === 'applicant').initialValue ? this.topFilterList.find(item => item.fieldName === 'applicant').initialValue : '',
            owenNo: this.topFilterList.find(item => item.fieldName === 'ownerNo').initialValue ? this.topFilterList.find(item => item.fieldName === 'ownerNo').initialValue : '',
            ownerName: this.topFilterList.find(item => item.fieldName === 'ownerName').initialValue ? this.topFilterList.find(item => item.fieldName === 'ownerName').initialValue : '',
            license: this.topFilterList.find(item => item.fieldName === 'license').initialValue ? this.topFilterList.find(item => item.fieldName === 'license').initialValue : '',
            remark: this.topFilterList.find(item => item.fieldName === 'remark').initialValue ? this.topFilterList.find(item => item.fieldName === 'remark').initialValue : '',
            itemIds: ID ? ID : '',
            tables: this.tableData
          };
          if (ID) {
            this.setPerformExecute(res);
          } else {
            this.$notify.success({ title: '提示信息', message: '没有解预留的配件！' });
          }
        });
      }
    },
    async setPerformExecute(val) {
      let resPerformExecute = await performExecute(val);

      // console.log(resPerformExecute, 'performExecute res----');
      if (resPerformExecute.resultCode === 200) {
        this.btn2 = true;
        this.$notify.success({ title: '提示信息', message: '解预留成功' });
        this.setPerformExecuteFlag = true;
        // console.log(this.dataSource, 'dataSource');
        // console.log(23423434, val.obligatedNo);

        let res = await queryPartObligatedItem({ obligatedNo: val.obligatedNo, ptype: this.ptype ? this.ptype : null });
        this.dataSource = [];
        this.dataSource = res.data;
        // this.dataSource.splice(0, this.dataSource.length, ...res.data);
        // this.$refs.table.EXECUTE_INSERT(res.data);

        // this.BaseTable.EXECUTE_DELETE(this.selectColumns);
        // this.searchDataToTable(this.topFilterList.find(item => item.fieldName === 'obligatedNo').initialValue);
      }
    },
    reset() {
      this.$refs.topFilter.RESET_FORM();
      this.BaseTable.EXECUTE_DELETE(this.tableData);
      this.btn = this.btn1 = this.btn2 = true;
      this.btn0 = false;
      this.yuliudan = false;
      for (let i = 0; i < this.topFilterList.length; i++) {
        this.topFilterList[i].readonly = false;
        if (i == 5 || i == 6 || i == 7 || i == 8) {
          this.topFilterList[i].disabled = true;
        } else {
          this.topFilterList[i].disabled = false;
        }
      }
    },
    toAddBtn() {
      this.visible2 = true;
      // this.btn = false;
      // this.btn0 = true;
      // this.yuliudan = true;
      // for (let i = 0; i < this.topFilterList.length; i++) {
      //   this.topFilterList[i].readonly = false;
      //   if (i == 0 || i == 1) {
      //     this.topFilterList[i].disabled = true;
      //   } else {
      //     this.topFilterList[i].disabled = false;
      //   }
      // }
      // this.columns.find(x => x.dataIndex === 'quantity').disabled = false;
      // this.topFilterList.find(item => item.fieldName === 'applicant').initialValue = +this.userId;
      // this.dataSource = [];
    },
    addHandle() {
      this.visible1 = true;
      this.handleType1 = 'add';
      this.btnDisabled = false;
      this.showHandler1();
    },
    delete(row) {
      this.handleType = 'edit';
      this.formData = row;
      this.$confirm('是否确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.itemId) {
          this.itemIds = this.itemIds + ',' + row.itemId;
        }
        this.$refs.table.EXECUTE_DELETE([row]);
        this.btn1 = false;
      });
    },
    async changeHandle(val) {
      val.ylcx = 1;
      this.fetchParams = Object.assign({}, val, {
        obligatedBeginDate: val.obligatedBeginDate ? val.obligatedBeginDate.split(' ')[0] : '',
        obligatedEndDate: val.obligatedEndDate ? val.obligatedEndDate.split(' ')[0] : ''
      });
      let res = await queryAllPartObligatedList(this.fetchParams);
      this.dataSource = res.data;
      // let param = '';
      // this.chooseFlag = 2;
      // for (let key in val) {
      //   for (let i = 0; i < this.topFilterList.length; i++) {
      //     if (key == this.topFilterList[i].fieldName) this.topFilterList[i].initialValue = val[key];
      //     if (key == 'obligatedNo') param = this.topFilterList.find(x => x.fieldName == 'obligatedNo').initialValue;
      //   }
      // }
      // this.searchDataToTable(param);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}品牌`;
      this.visible = true;
    },
    showHandler1() {
      this.dialogTitle1 = `新增预留`;
      this.visible1 = true;
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler1(val, type) {
      this.visible1 = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams1 = { ...this.fetchParams };
      }
    },
    async closeHandler2(val, type) {
      this.visible2 = val;
      console.log('refresh');
      let data = await this.$refs.topFilter.GET_FORM_DATA();
      this.changeHandle(data);
      let res1 = await queryAllPartObligatedList(this.fetchParams);
      this.dataSource = res1.data;
      // if (type === 'refresh') {
      //   // 重新加载
      //   this.fetchParams1 = { ...this.fetchParams };
      // }
    },
    closeHandlergongdan(val, type) {},
    searchAll() {
      this.dialogTitle = '查询预留单';
      this.obligatedNo = this.topFilterList.find(x => x.fieldName === 'obligatedNo').initialValue;
      this.visible = true;
      this.handleType = 'add';
    },
    getData(str, flag) {
      this.chooseFlag = 2;
      let arr = flag[0];
      let param = '';
      for (let key in arr) {
        for (let i = 0; i < this.topFilterList.length; i++) {
          if (key == this.topFilterList[i].fieldName) this.topFilterList[i].initialValue = arr[key];
          if (key == 'obligatedNo') param = arr[key];
        }
      }
      this.searchDataToTable(param);
      this.btnDisabled = this.btn0 = this.btn1 = true;
      this.topFilterList.find(item => item.fieldName === 'applicant').initialValue = +arr.applicant;
      this.topFilterList.find(item => item.fieldName === 'obligatedNo').disabled = true;
      this.topFilterList.find(item => item.fieldName === 'applicant').disabled = true;
      this.topFilterList.find(item => item.fieldName === 'ownerName').disabled = true;
      this.topFilterList.find(item => item.fieldName === 'license').disabled = true;
      this.topFilterList.find(item => item.fieldName === 'remark').disabled = true;
      this.btn2 = false;
    },
    async searchDataToTable(arr) {
      let res = await queryPartObligatedItem({ obligatedNo: arr });
      this.dataSource = res.data;
      // this.BaseTable.EXECUTE_INSERT(res.data);
    }
  }
};
</script>

<style lang="less" scoped></style>
